package VIEW;

import MODEL.LineUpModel;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

public class DisponibilidadeView extends javax.swing.JFrame {

    private ArrayList<LineUpModel> lineUpArray;
    private Object[][] data;
    
    public DisponibilidadeView(ArrayList<LineUpModel> lineUpArray) {
        this.lineUpArray = lineUpArray;
//        initComponents();
        povoaComponentes();
    }

    public DisponibilidadeView() {
        povoaComponentes();
    }

    private void povoaComponentes() {
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        
        //pega os locais dos shows
        ArrayList<String> nomeDasColunas = new ArrayList<>();
        nomeDasColunas.add("Selecionar");
        nomeDasColunas.add("LineUp");
        nomeDasColunas.add("Quantidade");
        String[] columnNames = nomeDasColunas.toArray(new String[nomeDasColunas.size()]);

        //trecho de código para criar os dados a serem utilizados na tabela

        this.data = new Object[lineUpArray.toArray().length][columnNames.length];

        int indexLine = 0;

        for (LineUpModel lineUp : lineUpArray) {

            for (int i = 0; i < columnNames.length; i++) {

                if (i == 0) {
                    data[indexLine][i] = false;
                } else if (i == 1) {
                    data[indexLine][i] = lineUpArray.get(indexLine).calendarToDataString(lineUpArray.get(indexLine).getData());
                } else if (i == 2) {
                    data[indexLine][i] = new Integer(0);
                }
            }

            indexLine++;
        }

        jTable1.setModel(new javax.swing.table.DefaultTableModel(data, columnNames) {

            @Override
            public boolean isCellEditable(int rowIndex, int mColIndex) {
                if(mColIndex == 2 || mColIndex == 0) 
                    return true;
                else
                    return false;
            }
            Class[] types = new Class[]{
                java.lang.Boolean.class, java.lang.Object.class, java.lang.Integer.class
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public void setValueAt(Object o, int i, int i1) {
                if(i1 == 0 || i1 == 2){
                    data[i][i1] = o;
                }
                super.setValueAt(o, i, i1);
            }
            
            
            
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        
        jButton1.setText("Prosseguir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Voltar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 221, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Rock In Rio - Ingressos");

        jScrollPane1.setPreferredSize(new java.awt.Dimension(324, 322));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "-", "-"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        jTable1.setPreferredSize(new java.awt.Dimension(300, 215));
        jScrollPane1.setViewportView(jTable1);

        jButton1.setText("Prosseguir");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Voltar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE)
                        .addComponent(jButton1)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 215, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed

        LineUpView lineUpView = null;
        try {
            lineUpView = new LineUpView();
        } catch (SQLException ex) {
            Logger.getLogger(DisponibilidadeView.class.getName()).log(Level.SEVERE, null, ex);
        }
        lineUpView.setLocationRelativeTo(null); 
        lineUpView.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        int index = 0;
        boolean habilitadoParaConfirmarPedido = false;
        
        ArrayList<LineUpModel> lineUpSelecionadas = new ArrayList<>();
        Integer totalSelecionados = 0;
        for(Object[] object : this.data) {
            
            boolean selected = (boolean) object[0];
                        
            if(selected){
                Integer quantidadeRequerida = (Integer) object[2];
                
                if(quantidadeRequerida <= 0){
                    JOptionPane.showMessageDialog(null, "Para a LineUp " + object[1] + " escolher uma quantidade maior que zero!");
                    return;
                }
                else{
                    
                    LineUpModel lineUp = lineUpArray.get(index);
                    
                    if(lineUp.getIngressosVendidos() >= lineUp.getCapacidade()){
                        JOptionPane.showMessageDialog(null, "Esgoratam os ingressos da LineUp " + object[1] + "!");
                        return;
                    }
                    else if(quantidadeRequerida + lineUp.getIngressosVendidos() > lineUp.getCapacidade()){
                        JOptionPane.showMessageDialog(null, "A LineUp " + object[1] + " possui apenas " + 
                                (lineUp.getCapacidade() - lineUp.getIngressosVendidos()) + " ingresso(s)!");
                        return;
                    }
                }
                totalSelecionados = totalSelecionados + quantidadeRequerida;
                lineUpArray.get(index).setSelecionados(quantidadeRequerida);
                lineUpSelecionadas.add(lineUpArray.get(index));
                habilitadoParaConfirmarPedido = true;
            }
            
            index++;
        }
        
        if(habilitadoParaConfirmarPedido){
            this.dispose();
            AssociarIngressosView AssociarIngressos = new AssociarIngressosView(lineUpSelecionadas, totalSelecionados);
            AssociarIngressos.setLocationRelativeTo(null);
            AssociarIngressos.setVisible(true);
        } else {
            JOptionPane.showMessageDialog(null, "Para prosseguir é preciso selecionar alguma Line Up e a quantidade de ingresso que deseja adquirir para a mesma.");
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    public static void main(String args[]) {

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(DisponibilidadeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(DisponibilidadeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(DisponibilidadeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(DisponibilidadeView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>





        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new DisponibilidadeView().setVisible(true);
            }
        });



    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
}
